package com.example.rabbitmq;

import com.example.Configuration;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * RabbitMQConnection 连接控制类
 */
public class RabbitMQConnection {
    /**
     * 根据配置项返回RabbitMQ连接
     * @return Connection 连接对象
     * @throws Exception 抛出Exception异常这里不进行处理
     */
    public static Connection getConnection()throws Exception{
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        //配置RabbitMQ主机
        factory.setHost(Configuration.HOST_NAME);
        factory.setUsername(Configuration.USER_NAME);
        factory.setPassword(Configuration.PASSWORD);
        factory.setVirtualHost(Configuration.VIRTUAL_HOST);
        factory.setPort(Configuration.PORT);
        //创建连接
        Connection connection = factory.newConnection();
        return connection;
    }

    /**
     * 获取通道对象
     * @param connection
     * @return
     * @throws Exception
     */
    public static Channel getChannel(Connection connection)throws Exception{
        Channel channel = connection.createChannel();
        return channel;
    }

    /**
     * 关闭连接
     * @param connection
     * @throws Exception
     */
    public static void close(Connection connection)throws Exception{
        if(connection == null)
            return;
        connection.close();
    }
}
